package orm

import (
	"bytes"
	"database/sql/driver"
	"fmt"
	"time"
)

/**
 * @Description: 时间
 */
type LocalTime struct {
	time.Time
}

func (t LocalTime) String() string {
	return t.Time.Format("2006-01-02 15:04:05")
}

func (t LocalTime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", t.Time.Format("2006-01-02 15:04:05"))
	return []byte(stamp), nil
}

func (t *LocalTime) UnmarshalJSON(b []byte) error {
	//格式化秒
	b = bytes.Trim(b, "\"") // 此除需要去掉传入的数据的两端的 ""
	ext, err := time.Parse("2006-01-02 15:04:05", string(b))
	if err == nil {
		*t = LocalTime{ext}
		return nil
	}
	return err
}

func (t LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *LocalTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = LocalTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

func (t LocalTime) Unix() (int64, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return 0, nil
	}
	return t.Time.Unix(), nil
}

/**
 * @Description: 日期
 */
type LocalDate struct {
	time.Time
}

func (t LocalDate) String() string {
	return t.Time.Format("2006-01-02")
}

func (t LocalDate) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", t.Time.Format("2006-01-02"))
	return []byte(stamp), nil
}

func (t *LocalDate) UnmarshalJSON(b []byte) error {
	//格式化秒
	b = bytes.Trim(b, "\"") // 此除需要去掉传入的数据的两端的 ""
	ext, err := time.Parse("2006-01-02", string(b))
	if err == nil {
		*t = LocalDate{ext}
		return nil
	}
	return err
}

func (t LocalDate) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *LocalDate) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = LocalDate{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

func (t LocalDate) Unix() (int64, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return 0, nil
	}
	return t.Time.Unix(), nil
}
